package com.flyfinger.pojo;

import java.lang.reflect.Method;

/**
 * @author zhouyp
 * @program code
 * @description 通信协议对象
 * @create 2020-06-13
 */
public class RpcRequestUtil {

	private RpcRequestUtil() {
	}

	public static RpcRequest initRpcRequestByMethodName(Class<?> clazz, String methodName, Object[] parameters) {
		if (!clazz.isInterface()) {
			throw new IllegalArgumentException("传入的类型不是接口，无法远程调用");
		}
		final String canonicalName = clazz.getCanonicalName();

		if (!canonicalName.contains("com.lagou.service")) {
			throw new IllegalArgumentException("传入的接口没有定义在common包中，无法远程调用");
		}

		final RpcRequest rpcRequest = new RpcRequest();

		rpcRequest.setRequestId(System.currentTimeMillis());
		rpcRequest.setClassName(clazz.getName());
		rpcRequest.setMethodName(methodName);
		rpcRequest.setParameters(parameters);

		final Method[] methods = clazz.getMethods();
		for (Method method : methods) {
			if (methodName.endsWith(method.getName())) {
				rpcRequest.setParameterTypes(method.getParameterTypes());
				return rpcRequest;
			}
		}
		throw new IllegalArgumentException("未找到指定的方法名，无法远程调用");
	}
}
